/*
* BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.center.web.action.selfmainten;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;

import com.sinodata.bsm.center.message.Messenger;
import com.sinodata.bsm.center.service.probe.ProbeLoadService;
import com.sinodata.bsm.center.service.probe.ProbeService;
import com.sinodata.bsm.center.util.web.Struts2Utils;
import com.sinodata.bsm.center.web.action.BaseAction;
import com.sinodata.bsm.common.message.ServiceMessage;
import com.sinodata.bsm.common.vo.Probe;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author wangyazhou
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-8-17 下午4:53:17          wangyazhou        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class ProbeAction extends BaseAction {

    private static final long serialVersionUID = -2359289598633838148L;

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private Long id;

    @Autowired
    private ProbeService probeService;

    @Autowired
    private ProbeLoadService probeLoadService;

    /**
     * 跳转到probe管理页面
     */
    public String common() {
        return "common";
    }

    @Override
    public Object getModel() {
        return null;
    }

    /**
     * 获取bsm 和 probe所在主机的当前时间
     * @return
     */
    public String getTimeVal() {

        JSONObject json = new JSONObject();
        json.element("bsm", sdf.format(new Date()));

        ServiceMessage message = new ServiceMessage();
        message.setSrvId("SystemService");
        message.setMethod("getCurrenTime");
        message.setParams(new Object[] {});
        String resp = "";
        try {
            resp = (String) Messenger.getInstance().sendSyncMessage(id, message);
        } catch (Exception e) {
            logger.error(e);
        }
        json.element("probe", resp);
        Struts2Utils.renderText(json.toString());
        return null;
    }

    /**
     * 获取bsm中指定probe中的资源数 跟 probe中实际拥用的资源数
     * @return
     */
    public String getResCnt() {
        JSONObject json = new JSONObject();
        json.element("bsm", probeLoadService.getReses(id).size() + "");

        ServiceMessage message = new ServiceMessage();
        message.setSrvId("ResService");
        message.setMethod("getResCount");
        message.setParams(new Object[] {});
        String resp[] = null;
        try {
            resp = (String[]) Messenger.getInstance().sendSyncMessage(id, message);
        } catch (Exception e) {
            logger.error(e);
        }
        json.element("probe", resp[0]);
        json.element("probenormal", resp[1]);
        json.element("probepaused", resp[2]);
        Struts2Utils.renderText(json.toString());

        return null;
    }

    /**
     * 获取probe中的任务数
     * @return
     */
    @SuppressWarnings("unchecked")
    public String getProbeTask() {
        JSONObject json = new JSONObject();
        ServiceMessage message = new ServiceMessage();
        message.setSrvId("SystemService");
        message.setMethod("getProbeTask");
        message.setParams(new Object[] {});
        String resp[] = null;
        try {
            resp = (String[]) Messenger.getInstance().sendSyncMessage(id, message);
        } catch (Exception e) {
            logger.error(e);
        }
        JSONArray array = new JSONArray();
        String[] list = resp[3].split("[,]");
        List<Detail> dlist = new ArrayList<Detail>();
        try {
            for (String str : list) {
                if (str == null || str.length() == 0) {
                    continue;
                }
                String[] tmp = str.split("#");
                Detail detail = new Detail();
                detail.setResId(tmp[0]);
                detail.setCollectId(tmp[1]);
                detail.setBeginTime(tmp[2]);
                detail.setRunTime(tmp[3]);
                dlist.add(detail);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        Collections.sort(dlist, new DetailSort());

        for (Detail d : dlist) {
            JSONObject obj = new JSONObject();
            obj.element("resid", d.getResId());
            obj.element("collect", d.getCollectId());
            obj.element("begin", d.getBeginTime());
            obj.element("time", d.getRunTime());
            array.add(obj);
        }

        json.element("total", resp[0]);
        json.element("real", resp[1]);
        json.element("run", resp[2]);
        json.element("detail", array);
        Struts2Utils.renderText(json.toString());

        return null;
    }

    /**
     * 获取probe虚拟机信息
     * @return
     */
    public String getProbeJVM() {
        JSONObject json = new JSONObject();
        ServiceMessage message = new ServiceMessage();
        message.setSrvId("SystemService");
        message.setMethod("getJvmInfo");
        message.setParams(new Object[] {});

        Calendar startDate = Calendar.getInstance();
        String resp[] = null;

        try {
            resp = (String[]) Messenger.getInstance().sendSyncMessage(id, message);
        } catch (Exception e) {
            logger.error(e);
        }

        Calendar endDate = Calendar.getInstance();
        long runtime = endDate.getTimeInMillis() - startDate.getTimeInMillis();
        double totaltime = (double) runtime / 1000;
        json.element("time", "" + totaltime);

        json.element("max", resp[0]);
        json.element("total", resp[1]);
        json.element("free", resp[2]);
        json.element("usable", Integer.parseInt(resp[0]) - Integer.parseInt(resp[1]) + Integer.parseInt(resp[2]));
        json.element("jdkver", resp[3]);
        json.element("jvmProvider", resp[4]);
        json.element("trap", resp[5]);
        Struts2Utils.renderText(json.toString());
        return null;
    }

    public String getJobDeatailList() {
        ServiceMessage message = new ServiceMessage();
        message.setSrvId("SystemService");
        message.setMethod("getRunningJobDetail");
        message.setParams(new Object[] {});
        String resp = "";
        try {
            resp = (String) Messenger.getInstance().sendSyncMessage(id, message);
        } catch (Exception e) {
            logger.error(e);
        }

        return "";
    }

    /**
     * 重启一个probe
     * @return
     */
    public String restartProbe() {
        probeService.stopProbe(id);
        return null;
    }

    /**
     * 跳转到probe诊断页面
     * @return
     */
    public String diagnosis() {
        request.setAttribute("id", id);
        request.setAttribute("probe", probeService.findById(id));
        return "diagnosis";
    }

    /**
     * 获取所有的probe列表
     */
    @SuppressWarnings({ "unchecked", "deprecation" })
    @Override
    public String list() throws Exception {
        List<Probe> list = probeService.findAllProbe();
        Collections.sort(list, new ProbeSort());
        JSONObject json = new JSONObject();
        JSONArray array = new JSONArray();
        for (Probe p : list) {
            JSONObject data = new JSONObject();
            String op = "";
            if (p.getStatus() == 3 || p.getStatus() == 2 || p.getStatus() == 4) {
                op = "<div style='width: 110px;align:center;'>&nbsp;&nbsp;<a class='probebutton' href='javascript:restart(" + p.getId() + ");'>重启</a>&nbsp;&nbsp;<a class='probebutton' href='javascript:checkStatus(" + p.getId() + ");'>诊断</a><div>";
            } else {
                op = "<div style='width: 110px;align:center;'>&nbsp;&nbsp;<a disabled class='probebutton' href='javascript:restart(" + p.getId() + ");'>重启</a>&nbsp;&nbsp;<a disabled class='probebutton' href='javascript:checkStatus(" + p.getId() + ");'>诊断</a><div>";
            }
            data.element("op", op);
            data.element("id", p.getId());
            data.element("status", "<div class='probestatus" + (p.getStatus() == 3 || p.getStatus() == 2 || p.getStatus() == 4 ? 3 : 5) + "'></div>");
            data.element("name", p.getName());
            data.element("ip", p.getIp());
            data.element("type", "<div  class='" + p.getType() + "'>" + p.getType() + "</div>");
            data.element("time", p.getStatus() == 3 ? p.getStartDate().toLocaleString() : "&nbsp;");
            data.element("task", p.getStatus() != 3 ? "&nbsp;" : p.getTaskCount() == null ? "&nbsp;" : p.getTaskCount());
            array.add(data);
        }
        json.element("iTotalRecords", list.size());
        json.element("iTotalDisplayRecords", list.size());
        json.element("aaData", array);
        renderText(json.toString());
        return null;
    }

    @Override
    public String execute() throws Exception {
        return "common";
    }

    @Override
    public String input() throws Exception {
        return null;
    }

    @Override
    public String save() throws Exception {
        return null;
    }

    @Override
    public String delete() throws Exception {
        return null;
    }

    @Override
    protected void prepareModel() throws Exception {

    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    @SuppressWarnings("rawtypes")
    class ProbeSort implements Comparator {
        public int compare(Object obj1, Object obj2) {
            Probe res1 = (Probe) obj1;
            Probe res2 = (Probe) obj2;
            if (Math.abs(res1.getStatus() - 3) > Math.abs(res2.getStatus() - 3)) {
                return 1;
            } else {
                return 0;
            }
        }
    }

    @SuppressWarnings("rawtypes")
    class DetailSort implements Comparator {
        public int compare(Object obj1, Object obj2) {
            Detail res1 = (Detail) obj1;
            Detail res2 = (Detail) obj2;
            if (Double.parseDouble(res1.getRunTime()) < Double.parseDouble(res2.getRunTime())) {
                return 1;
            } else {
                return 0;
            }
        }
    }

    class Detail {
        private String resId;
        private String collectId;
        private String beginTime;
        private String runTime;

        public String getResId() {
            return resId;
        }

        public void setResId(String resId) {
            this.resId = resId;
        }

        public String getCollectId() {
            return collectId;
        }

        public void setCollectId(String collectId) {
            this.collectId = collectId;
        }

        public String getBeginTime() {
            return beginTime;
        }

        public void setBeginTime(String beginTime) {
            this.beginTime = beginTime;
        }

        public String getRunTime() {
            return runTime;
        }

        public void setRunTime(String runTime) {
            this.runTime = runTime;
        }

    }

}
